package com.longrise.android.by.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.model.Share;
import com.longrise.android.byjk.model.ShareParams;
import com.longrise.android.byjk.permission.PermissionUtil;
import com.longrise.android.byjk.plugins.login.TipsActivity;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BaseFrameView;
import com.longrise.android.by.utils.BYContants;
import com.longrise.android.by.utils.BYUtil;
import com.longrise.android.ui.dialog.ShareDialog;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


/**
 * Created by godliness on 2017/3/3.
 * 保易相关页面
 * <p>
 * {
 * 产品点评
 * 公司点评
 * 保险案件
 * 计划对比
 * }
 */
public class BYWebActivity extends BaseActivity implements BaseFrameView.ReloadListener, BYWebView, View.OnClickListener {

    private static final String TAG = "BYWebActivity";

    private final int MSG_PAGE_START = 0;
    private final int MSG_PAGE_ERROR = 1;
    private final int MSG_PAGE_FINISH = 2;

    private BaseFrameView mBaseView;
    public WebView mWebView;
    private WebSettings mWebSettings;

    private Toolbar mToolbar;
    public RelativeLayout mShare;
    private ImageView mImageShare;
    private View mLoading;

    private String mUrl;
    private String mTitle = "";

    private boolean mIsError;
    private boolean mDestory;
    private boolean mFlag = true;

    private int mType = BYContants.PRODUCT_TPYE;  //根据当前类型加载相关页面

    private BYWebPresenter mPresenter;

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mDestory) {
                return;
            }
            switch (msg.what) {
                case MSG_PAGE_START:
                    mBaseView.setVisibility(View.VISIBLE);
                    mBaseView.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
                    mWebView.setVisibility(View.GONE);
                    break;

                case MSG_PAGE_ERROR:
                    mBaseView.setVisibility(View.VISIBLE);
                    mBaseView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
                    mWebView.setVisibility(View.GONE);
                    break;

                case MSG_PAGE_FINISH:
                    mBaseView.setVisibility(View.GONE);
                    mBaseView.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                    mWebView.setVisibility(View.VISIBLE);
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    public int getContentViewId(@Nullable Bundle state) {
        if (state != null) {
            mType = state.getInt(BYContants.BY_EXTRA_PARAMS);
        }else{
            getExtraData();
        }
        return R.layout.activity_productcom;
    }

    public void initPresenter() {
        mPresenter = new BYWebPresenter(this, mType);
        mPresenter.init();
    }

    @Override
    public void initView() {
        mBaseView = (BaseFrameView) findViewById(R.id.bf_procom);
        mBaseView.setOnReloadListener(this);
        mWebView = (WebView) findViewById(R.id.webview_procom);
        mWebView.setWebChromeClient(mWebChromeClient);
        mWebView.setWebViewClient(mWebViewClient);
        mLoading = findViewById(R.id.byweb_load);
        isLoading(false);
        initTitle();
        onEvent();
        setWebSetting();

        addGoogleTrace();
        initPresenter();
    }

    public void isLoading(boolean isLoad) {
        mLoading.setVisibility(isLoad ? View.VISIBLE : View.GONE);
    }

    /**
     * BYContants.CLIENT_MANAGER     客户管理
     * BYContants.XUQ_CEP            保易智评
     * BYContants.PRODUCT_TPYE       产品点评
     * BYContants.COMPANY_TYPE       公司点评
     * BYContants.TRYELIKE_TYPE      保险案件
     * BYContants.PLANCONSTART_TYPE  计划对比
     */
    private void getExtraData() {
        Intent extraIntent = getIntent();
        mType = extraIntent.getIntExtra(BYContants.BY_EXTRA_PARAMS, BYContants.PRODUCT_TPYE);
    }

    private void initTitle() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_close_main);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });
        mShare = (RelativeLayout) findViewById(R.id.bb_toolbar_right_rl);
        mImageShare = (ImageView) findViewById(R.id.iv_toolbar_share);

        if (mType == BYContants.PLANCONSTART_TYPE) {
            //计划界面无分享图标
            mShare.setVisibility(View.GONE);
        }
    }

    private void setWebSetting() {
        mWebSettings = mWebView.getSettings();

        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(absolutePath);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        //与js进行交互相关另起
        mWebView.addJavascriptInterface(BYWebCallback.getJavascriptInterface(mType, this), "bb");
    }

    private void onEvent() {
        if (mShare != null) {
            mShare.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bb_toolbar_right_rl) {
            mWebView.loadUrl("javascript:$_$.shareurl()");
        }
    }

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (TextUtils.isEmpty(url)) return true;
            if (url.endsWith(".pdf") || url.endsWith(".PDF")) {
                Intent pdfIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(pdfIntent);
                return true;
            }
            isLoading(true);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            try {
                if (mIsError) {
                    mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
                } else {
                    mIsError = false;
                    mHandler.sendEmptyMessageDelayed(MSG_PAGE_FINISH, 500);
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mTitle = view.getTitle();
                        boolean isShare = BYUtil.isVisiableShare(mTitle);
                        mShare.setVisibility(isShare ? View.VISIBLE : View.GONE);
                        //客户管理 || 需求测评 显示分享指引
                        if (!mDestory && isShare && (mType == BYContants.CLIENT_MANAGER || mType == BYContants.XUQ_CEP)) {
                            showTips();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mIsError = true;
        }
    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("error")) {
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            DZZWTools.showToast(BYWebActivity.this, message, 0);
            return true;
        }
    };

    @Override
    public void onReload(View v) {
        if (TextUtils.isEmpty(mUrl)) {
            mPresenter.request(this, mType);
        } else {
            load(mUrl);
        }
    }

    public void showShareDialog(ShareParams shareParams) {
        if (!isFinishing()) {
            ShareDialog shareDialog = new ShareDialog(this);
            shareDialog.setShareParame(shareParams);
            shareDialog.show();
        }
    }

    public void showShare(Share share) {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
//        oks.setDialogMode();
        oks.disableSSOWhenAuthorize();
        oks.setTitle(share.mTitle);
        oks.setTitleUrl(share.mUrl);
        String content = "";
        if (share.mContent.length() > 50) {
            content = share.mContent.substring(0, 50).replace("&amp;", "&");
            oks.setText(content);
        } else {
            oks.setText(share.mContent.replace("&amp;", "&"));
        }
//        oks.setImagePath(FolderConstants.ICON_DIR + "/logoshare.jpg");
        oks.setImageUrl(share.mIconUrl);
        oks.setUrl(share.mUrl);
        oks.setSiteUrl(share.mUrl);
        oks.show(this);
        Tracker_Google.getInstance().addEvent("insurance-assessment", "share", "分享需求测评");
    }

    /**
     * 新手提示
     */
    private void showTips() {
//        暂时不需要判断,每次进来都需要提示.
//        boolean b = Control.isbyShare();
//        if(!b){
//          return ;
//        }
        if (!mFlag) {
            return;
        }
        boolean e = "保易网需求分析测试".equals(mTitle);
        if (e) {
            int[] loc1 = new int[2];
            mImageShare.getLocationInWindow(loc1);
            int width = mImageShare.getWidth();
            int height = mImageShare.getHeight();
            int h1 = AppUtil.dip2px(20);
            int com = AppUtil.dip2px(8);
            int[] loc = {loc1[0] - com, loc1[1] - h1 - com, loc1[0] + width + com, loc1[1] + height - h1 + com};
            Intent intent = new Intent(this, TipsActivity.class);
            intent.putExtra("type", TipsActivity.BYSHARE_TIPS);
            intent.putExtra("location", loc);
            startActivity(intent);
            mFlag = false;
        }
    }

    private void close() {
        finish();
    }

    private void addGoogleTrace() {
        switch (mType) {
            case BYContants.CLIENT_MANAGER:
                Tracker_Google.getInstance().addGoogleScreenName("customer-management");
                break;

            case BYContants.XUQ_CEP:
                Tracker_Google.getInstance().addGoogleScreenName("insurance-assessment");
                break;

            case BYContants.COMPANY_TYPE:
                Tracker_Google.getInstance().addGoogleScreenName("公司点评");
                break;

            case BYContants.PRODUCT_TPYE:
                Tracker_Google.getInstance().addGoogleScreenName("产品点评");
                break;

            case BYContants.TRYELIKE_TYPE:
                Tracker_Google.getInstance().addGoogleScreenName("保险案件");
                break;

            default:
                break;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(BYContants.BY_EXTRA_PARAMS, mType);
    }

    private void release() {
        if (mWebView != null) {
            mWebView.removeAllViews();
        }
        if (mWebSettings != null) {
            mWebSettings.setJavaScriptEnabled(false);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void load(String url) {
        mUrl = url;
        mWebView.loadUrl(url);
    }

    @Override
    public void setTitle(String title) {
        mToolbar.setTitle(title);
    }

    @Override
    public void onRequestError() {
        mUrl = "";
        mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
    }

    @Override
    public void onRequestStart() {
        mHandler.sendEmptyMessage(MSG_PAGE_START);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDestory = true;
        release();
    }
}
